<script setup>
import Form from "@/components/common/Form";
import { useForm } from "@/hooks/web/useForm";
import { useValidator } from "@/hooks/web/useValidator";
import { reactive, ref, watch } from "vue";
import { ElDivider, ElMessage, ElMessageBox } from "element-plus";
import agentApi from "@/apis/agent";

import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({}),
  },
});

const { required, phone, maxlength, email } = useValidator();

const formSchema = reactive([
  {
    field: "agent_name",
    label: "渠道名称",
    component: "Input",
    colProps: {
      span: 24,
    },
  },
  {
    field: "account",
    label: "登录名称",
    component: "Input",
    colProps: {
      span: 24,
    },
  },
]);

const rules = reactive({
  agent_name: [required(), maxlength(50)],
  account: [required(), maxlength(50)],
});

const { formRegister, formMethods } = useForm();
const { setValues, getElFormExpose, getFormData } = formMethods;

watch(
  () => props.userInfo,
  (value) => {
    setValues(value);
  },
  {
    immediate: true,
    deep: true,
  }
);

const saveLoading = ref(false);

const save = async () => {
  const elForm = await getElFormExpose();
  const valid = await elForm?.validate().catch((err) => {
    console.log(err);
  });
  if (valid) {
    ElMessageBox.confirm("是否确认修改?", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(async () => {
        const model = await getFormData();
        try {
          saveLoading.value = true;
          await agentApi
            .updateInfo(model)
            .then((res) => {
              ElMessage.success("修改成功");
              userStore.setUserInfo(
                Object.assign({}, userStore.getUserInfo, model)
              );
            })
            .catch((e) => {
              console.log(e);
            });
        } catch (error) {
          console.log(error);
        } finally {
          saveLoading.value = false;
        }
      })
      .catch(() => {});
  }
};
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <ElDivider />
  <BaseButton type="primary" @click="save">保存</BaseButton>
</template>
